Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

18.4 Early Workqueue Initialization

This section covers the first half of the workqueue initialization process. Within the Linux kernel, workqueue_init_early() is the core initialization function of the workqueue subsystem. It is invoked during the early stages of system boot to establish the fundamental framework of the workqueue infrastructure before the system possesses the capability to create standard tracking threads. To better comprehend the workqueue initialization flow, the typical processing lifecycle of a single asynchronous task (described by a work_struct structure) is outlined below.

The workqueue subsystem in the Linux kernel acts as an asynchronous execution framework that defers task processing to the process context. Distinct from spawning a regular standalone process, the workqueue delegates the target task (callback function) to a specialized pool of background kernel threads generated by the kernel, designated as worker threads (Worker Threads). Throughout this processing lifecycle, the system coordinates three critical tracking structures to dictate who executes the task and how it is processed:

  • Work Item (struct work_struct):
    The minimal user-defined task payload block. It encloses a function pointer (referencing the explicit callback logic to be executed) alongside optional private context data.

  • Worker (struct worker):
    An active background kernel execution thread (typically named following the format kworker/uX:X) whose runtime loop is to continuously harvest pending work items from a queue and execute them.

  • Worker Pool (struct worker_pool):
    The administrative container managing an aggregated group of workers. Each individual CPU core typically manages exactly two worker pools: a normal-priority pool and a high-priority pool.

When a thread triggers an asynchronous task via schedule_work(), the kernel first resolves the targeted worker pool corresponding to the local CPU core, and appends the work item onto the tail boundary of a doubly linked list named worklist managed inside the worker pool structure (pool->worklist). Following this insertion, the kernel inspects the pool's vacant list (pool->idle_list) to check if any idle worker threads are readily available. If a vacant worker is discovered, the system awakens its process state (transitioning it from TASK_INTERRUPTIBLE / S over to TASK_RUNNING / R). Conversely, if no idle workers are available and all current execution threads are occupied, the kernel evaluates system load metrics to determine whether it should dynamically spin up a brand-new kworker thread instance.

The execution loop of a worker thread is structured as a continuous "harvest-and-process" routine. Upon being awakened, the worker thread enters the core function worker_thread(). It immediately inspects whether pool->worklist is empty; if the list contains pending tasks, it extracts the very first work_struct block situated at the head of the chain. Prior to executing the task, the kernel validates that the task operates within an appropriate context environment via a pool workqueue helper structure (struct pool_workqueue). The worker thread marks itself as actively working and subsequently triggers the callback function bound to the work item (the function referenced by work->func). At this juncture, the deferred task formally executes within the kernel space.

Modern Linux distributions manage these operations via the Concurrency Managed Workqueue (CMWQ) architecture. The underlying scheduling logic is engineered to keep CPU cores optimally busy without inducing system overloads. If an active worker thread drops into a low-power sleep phase while executing its task (such as blocking to wait for disk filesystem I/O), the kernel immediately detects the context switch and awakens an alternative worker thread from the pool to process the subsequent work item in the queue. Furthermore, the subsystem guarantees that an identical standalone work_struct block is strictly prohibited from executing concurrently across multiple CPU cores.

Once the specific function designated by the work item completes its execution (meaning work->func returns cleanly), the worker thread loops back to check if auxiliary tasks remain pending within the queue. If the worklist of the parent worker pool is completely exhausted, the worker thread is not instantly destroyed; instead, it appends itself to pool->idle_list and enters a low-power sleep state. The kernel reclaims and destroys the thread only if it remains unutilized over an extended idle window. If an external process is synchronously blocking to wait for the completion of this task, the worker thread triggers a wakeup pass to unblock that context.

In essence, the operational flow from user-space task submission to final execution involves appending a work descriptor onto a CPU's localized worker pool, awakening a dedicated kernel thread, and letting that thread execute the payload callback on behalf of the caller.

The workqueue_init_early() routine first initializes the diverse core data structures consumed by the workqueue subsystem, guaranteeing that subsequent system bootstrap phases (such as peripheral driver loading blocks) can reliably allocate and deploy workqueues. Upon initializing the global worker pools, workqueue tracking chains, and corresponding synchronization locks, it configures a specialized CPU mask designated as wq_unbound_cpumask to define the explicit subset of CPU cores that are eligible to execute unbound workqueue tasks. Furthermore, the function sets up and initializes exactly two default worker pools for every possible CPU core—a normal-priority pool and a high-priority (highpri) pool. Finally, it allocates the predefined, globally accessible standard system workqueues (such as system_wq, system_highpri_wq, and system_long_wq), exposing them directly to be consumed by other core kernel sub-modules.

The function workqueue_init_early() is defined within the core source file git/kernel/workqueue.c, and its definition is implemented as follows:

void __init workqueue_init_early(void)
{
	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
	int hk_flags = HK_FLAG_DOMAIN | HK_FLAG_WQ;
	int i, cpu;
	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(hk_flags));
	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
	for_each_possible_cpu(cpu) {
		struct worker_pool *pool;
		i = 0;
		for_each_cpu_worker_pool(pool, cpu) {
			BUG_ON(init_worker_pool(pool));
			pool->cpu = cpu;
			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
			pool->attrs->nice = std_nice[i++];
			pool->node = cpu_to_node(cpu);
			mutex_lock(&wq_pool_mutex);
			BUG_ON(worker_pool_assign_id(pool));
			mutex_unlock(&wq_pool_mutex);
		}
	}
	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
		struct workqueue_attrs *attrs;
		BUG_ON(!(attrs = alloc_workqueue_attrs()));
		attrs->nice = std_nice[i];
		unbound_std_wq_attrs[i] = attrs;
		BUG_ON(!(attrs = alloc_workqueue_attrs()));
		attrs->nice = std_nice[i];
		attrs->no_numa = true;
		ordered_wq_attrs[i] = attrs;
	}
	system_wq = alloc_workqueue("events", 0, 0);
	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
	system_long_wq = alloc_workqueue("events_long", 0, 0);
	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
					    WQ_UNBOUND_MAX_ACTIVE);
	system_freezable_wq = alloc_workqueue("events_freezable",  WQ_FREEZABLE, 0);
	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
					      WQ_POWER_EFFICIENT, 0);
	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
				  WQ_FREEZABLE |WQ_POWER_EFFICIENT,    0);
	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
	      !system_unbound_wq || !system_freezable_wq ||
	       !system_power_efficient_wq ||  !system_freezable_power_efficient_wq);
}

Before diving into the codebase breakdown, it is essential to outline two predefined architectural constants and two specific housekeeping flags:

  • NR_STD_WORKER_POOLS:
    Defines the absolute number of standard worker pools managed per CPU core, which typically evaluates to 2.

  • HIGHPRI_NICE_LEVEL:
    Establishes the fine-tuning priority offset value reserved for high-priority threads, commonly mapped to -20. A more negative nice value translates directly to a higher runtime scheduling priority for the process.

  • HK_FLAG_DOMAIN:
    The housekeeper scheduling domain flag. When this configuration flag is active, the corresponding CPU core is mandated to handle administrative housekeeping tasks associated with general scheduling domains.

  • HK_FLAG_WQ:
    The housekeeper workqueue flag. When this flag is enabled, the assigned CPU core assumes responsibility for processing background operations tied to the workqueue subsystem.

The leading static assertion, BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long)), guarantees that the pool_workqueue structure strictly complies with an 8-byte memory alignment boundary. If the compiler encounters a layout violation that fails this alignment criterion, it triggers a compilation error. The subsequent statement dynamic allocates memory for the CPU bitmask variable wq_unbound_cpumask, throwing a fatal error alarm if the allocation cycle fails. Following this allocation, the initialization routine invokes housekeeping_cpumask() to retrieve the active housekeeper CPU bitmask, and transfers this layout over to wq_unbound_cpumask via cpumask_copy().

The core operational objective of this line is to ensure that asynchronous tasks managed within unbound workqueues (unbound workqueue) are strictly constrained to execute exclusively on CPU cores that simultaneously participate in scheduling domain orchestration and assume workqueue housekeeping responsibilities. Consequently, if a specific CPU core is isolated via the user-space isolcpus boot parameter, it is automatically filtered out and excluded from participating in the HK_FLAG_WQ mask tracking index.

The assignment pwq_cache = KMEM_CACHE() carves out a lookaside allocation pool within the slab allocator to house the pool_workqueue (pwq) nodes, storing the base address of this pool registry into the pointer pwq_cache. If this memory allocation pass encounters a failure, a kernel panic crash is instantly raised. Within the Concurrency Managed Workqueue (CMWQ) architecture of the Linux kernel, the pool_workqueue structure serves as the core intermediary layer linking high-level workqueues to the low-level worker thread pools. It acts as a multi-to-one mapping layout bridging the user-facing task queue abstractions (struct workqueue_struct) with the low-level executing worker pools (struct worker_pool). A standalone workqueue (such as the default system_wq) maps explicitly to a unique pwq instance across every individual CPU core or NUMA node, which records the runtime configuration constraints (such as the maximum concurrency limit max_active) governing that specific workqueue's footprint on that local core or node.

The subsequent loop module initializes all available worker pools across each individual CPU core. Within this loop logic path, the subsystem invokes init_worker_pool() to initialize the internal tracking linked lists and hash tables consumed by the pool, while resetting the remaining administrative fields to their default states. Following this, it initializes the pool's local CPU index tracking field, its parent NUMA node tracking field, alongside the target execution priority nice offset and mask fields enclosed within the pool's attribute structure. At the conclusion of this loop block, the routine calls worker_pool_assign_id() to assign a unique numerical identification token to each initialized pool instance.

The final loop block dynamic allocates memory to hold the attribute descriptor structures (struct workqueue_attrs) for unbound and ordered workqueues, which map out their distinct execution properties (such as regulating which CPU subsets they can execute on, what priority nice tier they possess, and which NUMA node affinity constraints they honor). It simultaneously initializes the default configuration profiles for these arrays, storing the base memory addresses of these allocated attributes inside the tracking arrays unbound_std_wq_attrs[] and ordered_wq_attrs[], respectively.

Finally, workqueue_init_early() allocates memory for several predefined, globally accessible system workqueues. These pre-allocated system queues encompass:

  • system_wq:
    The system-default and most widely utilized Concurrency Managed Workqueue (CMWQ) instance. When a subsystem does not mandate its own dedicated kernel thread pool and merely requires the asynchronous execution of a basic callback function, this queue serves as the primary engineering solution.

  • system_highpri_wq (System High-Priority Workqueue):
    A specialized, predefined workqueue within the Linux kernel. While structurally analogous to system_wq, it diverges fundamentally in its scheduling precedence and execution responsiveness. Conversely, system_long_wq is designed under an inverse principle: its objective is not to maximize execution velocity, but to prevent hot path pipeline obstruction. When a task is anticipated to possess a long runtime footprint or encloses operations prone to introducing prolonged context blocking (such as deep disk filesystem I/O), it must be explicitly shunted over to system_long_wq.

  • system_unbound_wq (System Unbound Workqueue):
    The most unique architectural component within the Linux workqueue framework. Diverging from the previously detailed system_wq or system_highpri_wq setups, it shatters the traditional "one worker pool per CPU core" boundary constraint and is engineered specifically to accommodate compute-heavy CPU-bound tasks or long-blocking workloads. Standard workqueues are tightly bound to a Per-CPU topology—meaning a task is queued and executed within the worker pool of the exact CPU core where it was originally submitted. Conversely, system_unbound_wq is explicitly flagged with the WQ_UNBOUND operational bitmask; tasks routed here are decoupled from any specific CPU affinity and can be dispatched onto any authorized core across the entire system. Although this design drops processor cache locality advantages (Cache Locality), it yields significantly higher scheduling flexibility. Its existence primarily prevents critical hot path tasks from being disrupted while driving up parallel throughput metrics.

  • system_freezable_wq:
    A specialized workqueue designed specifically to cooperate with the kernel's power management architecture (suspend/resume loops). When the operating system prepares to enter a low-power sleep phase (such as a Suspend-to-RAM or Hibernate cycle), the execution of tasks inside this queue is frozen. Throughout a Linux suspend sequence, the kernel must guarantee that all tasks capable of disrupting memory snapshot writebacks or state transitions across hardware devices are completely stopped. When the kernel triggers the global Freeze process, this queue instantly halts the dispatching of new work items and forces active workers into a deterministic, controlled state.

  • system_power_efficient_wq:
    An execution framework acting as an energy efficiency mediator within the kernel's power optimization layers. Its primary technical design objective is to balance task urgency constraints against absolute system power dissipation metrics. The defining characteristic of system_power_efficient_wq is that its runtime behavior scales dynamically based on the state of the kernel configuration parameter workqueue.power_efficient. Under baseline conditions (where power-saving mode is turned off), it behaves identically to system_wq; tasks are tightly bound to execute on the specific CPU core that submitted them to preserve optimal cache locality. Conversely, when power-saving mode is active, it drops its processor affinity and transitions to adopt unbound characteristics.Building upon this layer, system_freezable_power_efficient_wq represents a combined framework that unifies both power management freeze controls and dynamic power-efficiency scheduling. It functions as an energy-conscious executor that automatically suspends operations prior to system hibernation. During early boot initialization, this queue is explicitly instantiated with both the WQ_FREEZABLE and WQ_POWER_EFFICIENT capability flags. Tasks residing here are strictly mandated to halt whenever a system suspend sequence is raised, and the scheduler prefers to route their execution onto CPU cores that are already awake, which minimizes total processor wake-up counts. This dual behavior elegantly solves two major engineering hurdles for background polling routines on mobile and embedded hardware: optimizing battery conservation and ensuring safe system suspend cycles. Under standard runtime operations, it avoids waking up sleeping CPU cores; during a system shutdown or hibernation pass, it guarantees that these background workloads are completely drained and blocked from attempting to interface with physical hardware at the exact moment devices lose power, thereby preventing system crashes.

At the very conclusion of the early initialization routine, the kernel leverages the assertion macro BUG_ON() to verify that the memory allocations for all these critical system workqueues have succeeded.

Copyright © 2026 Guangzhou eSmart Information Technology Co., Ltd. All Rights Reserved.
All content in this book is copyrighted by the author. For personal learning and exchange only. Commercial use without authorization is strictly prohibited. Email:

✉ 3348194517@qq.com | hai616878@gmail.com